<template>
  <div class="body">
    <el-form ref="ruleForm" :rules="rules" :model="mdl" label-width="110px">
      <el-form-item label="店铺图片" required>
        <el-upload
          ref="upload"
          list-type="picture-card"
          action
          :file-list="fileList"
          :show-file-list="true"
          :http-request="uploadFile"
          multiple
          accept="image/gif,image/jpeg,image/jpg,image/png,image/svg"
          :limit="5"
          :on-change="handlePreview"
          :on-exceed="handleExceed"
          :on-remove="handeRemove"
        >
          <i class="el-icon-plus" />
        </el-upload>
      </el-form-item>
      <!-- <el-form-item label="路线图" required>
        <el-upload
          ref="upload"
          list-type="picture-card"
          action
          :file-list="fileList1"
          :show-file-list="true"
          :http-request="uploadFile1"
          multiple
          accept="image/gif,image/jpeg,image/jpg,image/png,image/svg"
          :limit="5"
          :on-change="handlePreview1"
          :on-exceed="handleExceed1"
          :on-remove="handeRemove1"
        >
          <i class="el-icon-plus" />
        </el-upload>
      </el-form-item> -->
      <el-form-item label="店铺名称" required>
        <el-input v-model="mdl.storeName" placeholder="请输入店铺名称" />
      </el-form-item>
      
      <el-form-item label="店铺经纬度" required>
        <baidu-map  
          class="map" 
          :center="center" 
          :zoom="zoom"   
          :scroll-wheel-zoom="true" 
          @ready="handler" 
          @click="clickBmap">
            <bm-marker
              :position="markerPo"
              :dragging="true"
              :zIndex="999999999"
            >
            </bm-marker>
            <bm-geolocation
              anchor="BMAP_ANCHOR_BOTTOM_RIGHT"
              :showAddressBar="true"
              :autoLocation="true"
            ></bm-geolocation>
          </baidu-map>
      </el-form-item>
      
      <el-form-item label="详细地址" required>
        <el-input v-model="mdl.address" placeholder="请输入店铺地址" />
      </el-form-item>
      <el-form-item label="店铺介绍" required>
        <el-input
          v-model="mdl.introduce"
          type="textarea"
          placeholder="请输入店铺介绍"
        />
      </el-form-item>
      
      <!-- <el-form-item label="美团店铺session">
        <el-input
          v-model="mdl.mtStoreSession"
          type="textarea"
          placeholder="请输入美团店铺session"
        />
      </el-form-item> -->
      <!-- <el-form-item label="美团店铺id">
        <el-input
          v-model="mdl.mtStoreId"
          type="textarea"
          placeholder="请输入美团店铺id"
        />
      </el-form-item> -->

      <!-- <el-form-item label="店铺注意事项" required>
        <el-input
          v-model="mdl.matters"
          type="textarea"
          placeholder="请输入店铺注意事项"
        />
      </el-form-item> -->
      <el-form-item label="预约低消" required>
        <el-select v-model="mdl.lowConsumeTime" placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
          小时
      </el-form-item>
      <el-form-item label="大门锁id" required>
        <el-input v-model="mdl.lockCode" placeholder="请输入大门锁id" />
      </el-form-item>
      <el-form-item label="营业时间" required>
        <el-input
          v-model="mdl.step"
          type="textarea"
          placeholder="请输入营业时间"
        />
      </el-form-item>
      
      <el-form-item label="联系人" required>
        <el-input v-model="mdl.name" placeholder="请输入联系人" />
      </el-form-item>
      <el-form-item label="手机号" required>
        <el-input v-model="mdl.mobile" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="wifi账号" required>
        <el-input v-model="mdl.wifiName" placeholder="请输入wifi账号" />
      </el-form-item>
      <el-form-item label="wifi密码" required>
        <el-input v-model="mdl.wifiPassword" placeholder="请输入wifi密码" />
      </el-form-item>
      <el-form-item label="用户协议" required>
        <quill-editor v-model="mdl.platformAgreement" ref="myQuillEditor" :options="editorOption">
        </quill-editor>
      </el-form-item>
      <!-- <el-row>
        <el-col :span="24">
          <el-form-item>
            <el-button
            style="margin-bottom:10px"
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="addTimeSlot"
        >新增</el-button>
            <el-table :data="storeWifiList">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="wifi名称" align="center">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.wifiName" placeholder="请输入"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="wifi密码" align="center">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.wifiPassword" placeholder="请输入"></el-input>
                  </template>
                </el-table-column>
                <el-table-column
                    fixed="right"
                    label="操作"
                    width="100">
                    <template slot-scope="scope">
                        <el-button type="text" size="small" @click="closeTimeSlot(scope.$index,scope.row)">移除</el-button>
                    </template>
                </el-table-column>
            </el-table>
          </el-form-item>
         </el-col>
      </el-row> -->
      <!-- <el-row>
        <el-col :span="12">
          <el-form-item label="商品营业时间" required>
            <el-time-picker
              value-format="HH:mm:ss"
              v-model="mdl.shopStartTime"
              :picker-options="{
                selectableRange: '00:00:00 - 23:59:00'
              }"
              placeholder="请选择">
            </el-time-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="商品结束时间" required>
            <el-time-picker
              value-format="HH:mm:ss"
              v-model="mdl.shopEndTime"
              :picker-options="{
                selectableRange: '00:00:00 - 23:59:00'
              }"
              placeholder="请选择">
            </el-time-picker>
          </el-form-item>
        </el-col>
      </el-row> -->
      <!-- <el-row> -->
        <!-- <el-col :span="12"> -->
          <!-- <el-form-item label="密码" required>
            <el-input v-model="mdl.mobile" placeholder="请输入密码" />
          </el-form-item> -->
        <!-- </el-col> -->
        <!-- <el-col :span="12">
          
          _
        </el-col> -->
        <!-- <el-col :span="12">
          <el-form-item label="wifi密码" required>
            <el-input v-model="mdl.wifiPassword" placeholder="请输入wifi密码" />
          </el-form-item>
        </el-col> -->
      <!-- </el-row> -->
      
      <!-- <el-row>
        <el-col :span="12">
          <el-form-item label="地区" required>
            <el-cascader v-model="mdl.quCode" :props="props" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="门锁编号" required>
            <el-input v-model="mdl.lockCode" placeholder="请输入门锁编号" />
          </el-form-item>
        </el-col>
      </el-row> -->
      <el-form-item label="店铺类型" required>
      <el-row>
        <!-- <el-col :span="12">
          <el-form-item label="店铺类型" required>
            <el-select v-model="mdl.type" placeholder="请选择">
              <el-option :value="0" label="先付"/>
              <el-option :value="1" label="后付"/>
            </el-select>
          </el-form-item>
        </el-col> -->
        <el-col :span="12">
          <el-form-item label="是否开启" required>
            <el-switch
              v-model="mdl.status"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </el-form-item>
        </el-col>
      </el-row>
      </el-form-item>
    </el-form>
    <div class="foot_btn">
      <el-button
        type="primary"
        :loading="submitLoading"
        @click="submitForm('ruleForm')"
        >提交</el-button
      >
      <el-button @click="handleCloseDrawer">取消</el-button>
    </div>
  </div>
</template>

<script>
import { fileUpload, addStore, updateStore, selectRegion } from "@/api/user";
import BmMarker from "vue-baidu-map/components/overlays/Marker";
import {
  quillEditor
} from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
export default {
  components: {
    BmMarker,
    quillEditor
  },
  name: "FormModel",
  props: {
    mdl: {
      type: Object,
      required: true,
    },
    handleCloseDrawer: {
      type: Function,
      required: true,
    },
  },
  data() {
    return {
      editorOption: {},
      submitLoading: false,
      fileList: [],
      uploadData: null,
      uploadData1: null,
      imgList: [],
      imgList1: [],
      fileList1: [],
      center: {lng: 0, lat: 0},
      zoom: 3,
      markerPo: {
        lng: 39.9,
        lat: 116.3,
      },
      storeWifiList:[],
      value:[],
      props: {
        lazy: true,
        lazyLoad(node, resolve) {
          const { level, value } = node;
          console.log(node);
          selectRegion({
            regionCode: value || "",
            regionLevel: level,
          }).then((res) => {
            console.log(res);
            console.log("111");
            const nodes = res.data.map((item) => ({
              value: item.regionCode,
              label: item.regionName,
              // leaf: item.regionLevel
            }));
            resolve(nodes);
          });
          // setTimeout(() => {
          //   const nodes = Array.from({ length: level + 1 })
          //     .map(item => ({
          //       value: ++id,
          //       label: `选项${id}`,
          //       leaf: level >= 2
          //     }))
          //     // 通过调用resolve将子节点数据返回，通知组件数据加载完成
          //   resolve(nodes)
          // }, 1000)
        },
      },
      rules:{
        account: [
          { required: true, message: "请输入平台账号", trigger: "blur" },
          { pattern: /^[a-zA-z]\w{3,15}$/, message: '只能包含字母、数字', trigger: 'blur' }
        ]
      },
      options: [{
          value: '1',
          label: '1'
        }, {
          value: '2',
          label: '2'
        }, {
          value: '3',
          label: '3'
        }, {
          value: '4',
          label: '4'
        }],
    };
  },
  mounted() {

    if(this.mdl.storeImg.length){
      this.mdl.storeImg.map(item => {
        this.fileList.push({
          url: item
        })
      })
      this.imgList = this.mdl.storeImg
    }
    // if(this.mdl.roadMap.length){
    //   this.mdl.roadMap.map(item => {
    //     this.fileList1.push({
    //       url: item
    //     })
    //   })
    //   this.imgList1 = this.mdl.roadMap
    // }
    if(this.mdl.lowConsumeTime){
      this.mdl.lowConsumeTime = +this.mdl.lowConsumeTime / 60
    }
    
    if(this.mdl.longitude){
      let latLon = this.qqMapTransBMap(this.mdl.longitude,this.mdl.latitude)
      this.center.lng = latLon.lng
      this.center.lat = latLon.lat
      this.markerPo.lng = latLon.lng
      this.markerPo.lat = latLon.lat
      this.zoom = 20
    }
    // if(this.mdl.storeWifiList.length){
    //   this.storeWifiList = []
    //   this.mdl.storeWifiList.map(res=>{
    //     this.storeWifiList.push({
    //       wifiName:res.wifiName,
    //       wifiPassword:res.wifiPassword
    //     })
    //   })
    // }
    
    console.log(this.center)
  },
  methods: {

    // 新增wifi
    addTimeSlot(){
      let arr = {
        wifiName:'',
        wifiPassword:''
      }
      this.storeWifiList.push(arr)
      // this.tableIndex = this.storeWifiList.length-1
    },

    // 删除wifi
    closeTimeSlot(index,item){
      this.$confirm('确认删除？').then(_ => {
        this.storeWifiList.splice(index,1)
      })
      .catch(_ => {

      })
    },

    clickBmap(val) {
      //右击鼠标放标注
      this.markerPo = val.point;
      this.center.lng = val.point.lng
      this.center.lat = val.point.lat
      this.zoom = 20
      let obj = this.convert2TecentMap(val.point.lng,val.point.lat)
      console.log(obj)
      
      this.mdl.longitude=obj.lng;
      this.mdl.latitude=obj.lat;
      console.log(this.mdl);
    },
    handler ({BMap, map}) {
      console.log(BMap, map)
      // this.center.lng = 116.404
      // this.center.lat = 39.915
      // this.zoom = 15
    },
    // 百度地图转腾讯-经纬度
    convert2TecentMap(lng, lat) {
      if (lng == '' && lat == '') {
        return {
          lng: '',
          lat: ''
        }
      }
      var x_pi = 3.14159265358979324 * 3000.0 / 180.0
      var x = lng - 0.0065
      var y = lat - 0.006
      var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi)
      var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi)
      var qqlng = z * Math.cos(theta)
      var qqlat = z * Math.sin(theta)
      return {
        lng: qqlng,
        lat: qqlat
      }
    },

    // 腾讯转百度-经纬度
    qqMapTransBMap(lng, lat) {
      let x_pi = 3.14159265358979324 * 3000.0 / 180.0;
      let x = lng;
      let y = lat;
      let z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
      let theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
      let lngs = z * Math.cos(theta) + 0.0065;
      let lats = z * Math.sin(theta) + 0.006;
    
      return {
          lng: lngs,
          lat: lats 
      } 
    },



    // getLocation() {
    //   window.open("https://www.opengps.cn/Map/Tools/PickUpGPS_AMap.aspx");
    // },

    // 移除上传图片
    handeRemove(e){
      console.log(e)
      let index = this.imgList.findIndex(item => item == e.url)
      
      this.imgList.splice(index, 1)
      console.log(this.imgList)
    },

    // 上传图片
    uploadFile(e) {
      fileUpload(this.uploadData).then((res) => {
        if (res) {
          console.log(res);
          // this.mdl.storeImg.push(res.data)
          this.imgList.push(res.data);
          this.$message({
            message: "上传成功",
            type: "success",
          });
          console.log(res);
        } else {
          this.$message.error(res.status);
        }
      });
    },
    handleExceed(file) {
      this.$message({
        message: "最多只允许上传五张",
        type: "warning",
      });
    },
    // 获取上传文件信息
    handlePreview(file) {
      const _this = this;
      var formData = new FormData();
      formData.append("file", file.raw);
      console.log(formData);
      _this.uploadData = formData;
    },

    // 路线图
    // 移除上传图片
    handeRemove1(e){
      console.log(e)
      let index = this.imgList1.findIndex(item => item == e.url)
      
      this.imgList1.splice(index, 1)
      console.log(this.imgList1)
    },
    // 上传图片
    uploadFile1(e) {
      fileUpload(this.uploadData1).then((res) => {
        if (res) {
          console.log(res);
          // this.mdl.storeImg.push(res.data)
          this.imgList1.push(res.data);
          this.$message({
            message: "上传成功",
            type: "success",
          });
          console.log(res);
        } else {
          this.$message.error(res.status);
        }
      });
    },
    handleExceed1(file) {
      this.$message({
        message: "最多只允许上传五张",
        type: "warning",
      });
    },
    // 获取上传文件信息
    handlePreview1(file) {
      const _this = this;
      var formData = new FormData();
      formData.append("file", file.raw);
      console.log(formData);
      _this.uploadData1 = formData;
    },

    // 提交
    submitForm(isContinue) {
      // 提交请求
      this.mdl.storeWifiList = this.storeWifiList
      this.mdl.lowConsumeTime = +this.mdl.lowConsumeTime * 60
      console.log(this.mdl);

      if(this.mdl.status){
        this.mdl.status = 'use'
      }else{
        this.mdl.status = 'stop'
      }
      // if (!this.mdl.storeId) {
        this.mdl.storeImg = this.imgList;
        this.mdl.roadMap = this.imgList1;
      // }

      const request = this.mdl.storeId
        ? updateStore(this.mdl)
        : addStore(this.mdl);
      request
        .then((res) => {
          if (res.statusCode === "00000") {
            this.$message({ message: "提交成功", type: "success" });
            // 关闭弹窗
            this.handleCloseDrawer();
            // 调用父级组件刷新数据
            this.$emit("getList");
          }
        })
        .catch((error) => {
          console.log(error);
        })
        .finally(() => {});
    },
  },
};
</script>

<style lang="less" scoped>
.map {
  width: 100%;
  height: 400px;
}
.body {
  padding-right: 25px;
  position: relative;
  height: 700px;
  overflow: auto;
  .showImg {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .goLocaton {
    position: absolute;
    top: 0;
    left: 980px;
  }
  .foot_btn {
    width: 150px;
    margin: 0 auto;
  }
}

/deep/ .el-checkbox__label {
  font-size: 12px;
}
</style>
